package main

import (
	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/cookie"
	"github.com/robin/webook/internal/repository"
	"github.com/robin/webook/internal/repository/dao"
	"github.com/robin/webook/internal/service"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"strings"
	"time"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"github.com/robin/webook/internal/web"
)

var (
	store = cookie.NewStore([]byte("secret"))
)

func main() {

	db := initDb()
	db = db.Debug()

	server := initWebServer()

	initUserHdl(server, db)
	err := server.Run(":8080")
	if err != nil {
		panic(err)
	}
}

func initWebServer() *gin.Engine {
	server := gin.Default()
	server.Use(Cors())
	server.Use(sessions.Sessions("mysession", store))

	return server
}

func initDb() *gorm.DB {
	db, err := gorm.Open(mysql.Open("root:root@tcp(localhost:13316)/webook?charset=utf8mb4&parseTime=True&loc=Local"))
	if err != nil {
		panic(err)
	}

	err = dao.InitTable(db)
	if err != nil {
		panic(err)
	}

	return db
}

func initUserHdl(server *gin.Engine, db *gorm.DB) {
	userDao := dao.NewUserDao(db)
	repo := repository.NewUserRepository(userDao)
	svc := service.NewUserService(repo)
	uh := web.NewUserHander(svc)
	uh.RegisterRoutes(server)
}

// Cors 跨域中间件
func Cors() gin.HandlerFunc {
	config := cors.Config{
		AllowCredentials: true,
		AllowHeaders:     []string{"content-type"},
		AllowOriginFunc: func(origin string) bool {
			if strings.HasPrefix(origin, "http://localhost") ||
				strings.HasPrefix(origin, "https://localhost") {
				return true
			}

			return strings.Contains(origin, "your_company.com")
		},
		MaxAge: 12 * time.Hour,
	}

	return cors.New(config)
}
